<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryList.query" clearable @clear="search">
                        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- el-table 中 data绑定数据源 -->
            <el-table
            :data="userList"
            style="width: 100%" border stripe>
                <el-table-column
                 type="index">
                </el-table-column>
                <el-table-column
                    prop="username"
                    label="姓名"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="mobile"
                    label="电话">
                </el-table-column>
                <el-table-column
                    prop="role_name"
                    label="角色">
                </el-table-column>
                <el-table-column
                    prop="mg_state"
                    label="状态">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.mg_state" @change="handleUserState(scope.row)">
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="address"
                    label="操作"
                    width="230px">
                  <template slot-scope="scope">
                    <el-tooltip content="删除" placement="top" :enterable="false">
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDelMessageBox(scope.row.id)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="修改" placement="top" :enterable="false">
                      <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="设置" placement="top" :enterable="false">
                      <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
            </el-table>
            <!-- 显示分页条的数据 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryList.pagenum"
              :page-sizes="[1, 3, 5]"
              :page-size="1"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </el-card>
        <!-- 这是一个对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="50%" @close="addDialogClosed">
          <el-form :model="adduser" :rules="adduserRules" ref="adduserRefs" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="adduser.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="adduser.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="adduser.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="adduser.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 这是修改用户的对话框 -->
        <el-dialog
          title="提示"
          :visible.sync="editDialogVisible"
          width="50%" @close="editFormClosed">
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRefs" label-width="70px">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 这是修改用户角色的对话框 -->
        <el-dialog
          title="修改用户角色"
          :visible.sync="setRolesVisiable"
          width="50%" @close="closeSetRolesDialog">
          <p>当前的用户： {{roleInfo.username}}</p>
          <p>当前的角色： {{roleInfo.role_name}}</p>
          <p>
            分配新角色：<el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
          </p>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRolesVisiable = false">取 消</el-button>
            <el-button type="primary" @click="setRolesInfo">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryList: {
        query: '',
        pagenum: 1,
        pagesize: 1
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      adduser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      adduserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 3, max: 40, message: '长度在 3 到 10 个字符', trigger: 'blur' },
          { validator: checkEmail }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 10, max: 11, message: '你输入的长度不正确', trigger: 'blur' },
          { validator: checkMobile }
        ]
      },
      editDialogVisible: false,
      // 修改表单信息
      editForm: {},
      // 修改表单的相关规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 显示与隐藏设置角色对话框
      setRolesVisiable: false,
      // 这是当前用户角色信息
      roleInfo: {},
      // 这是所有角色的信息
      roleList: [],
      // 这是下拉框信息
      selectRoleId: ''
    }
  },
  created: function () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryList
      })
      if (res.meta.status !== 200) return this.$message.error('获取管理员列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryList.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryList.pagenum = newPage
      this.getUserList()
    },
    async handleUserState (user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      return this.$message.success('更新用户状态成功')
    },
    search () {
      this.getUserList()
    },
    addDialogClosed () {
      this.$refs.adduserRefs.resetFields()
    },
    addUser () {
      this.$refs.adduserRefs.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.adduser)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.getUserList()
        this.dialogVisible = false
      })
    },
    // 显示修改用户的对话框
    async showEditDialog (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改表单的重置操作
    editFormClosed () {
      this.$refs.editFormRefs.resetFields()
    },
    // 修改表单 预验证和提交
    editUserInfo () {
      this.$refs.editFormRefs.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('表单修改失败')
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('表单修改成功')
      })
    },
    async showDelMessageBox (id) {
      const messageBox = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (messageBox === 'cancel') return this.$message.info('你已经取消了删除操作')
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.err('删除操作失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    async setRoles (role) {
      // 在显示用户角色信息之前拿到该用户信息
      // console.log(role)
      this.roleInfo = role
      // 获取所用角色的信息
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      this.roleList = res.data
      this.setRolesVisiable = true
    },
    // 保存用户修改的角色信息
    async setRolesInfo () {
      if (!this.selectRoleId) return this.$message.error('请选择需要分配的角色')
      const { data: res } = await this.$http.put(`users/${this.roleInfo.id}/role`, {
        rid: this.selectRoleId
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新角色失败')
      this.$message.success('更新角色成功')
      this.getUserList()
      this.setRolesVisiable = false
    },
    // 关闭设置用户角色的对话框
    closeSetRolesDialog () {
      this.selectRoleId = ''
      this.roleInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>

</style>
